/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.service.impl;

import me.zhengjie.modules.system.domain.GodownEntry;
import me.zhengjie.modules.system.domain.GodownEntryDetail;
import me.zhengjie.modules.system.domain.PurchaseData;
import me.zhengjie.modules.system.repository.GodownEntryRepository;
import me.zhengjie.modules.system.repository.PurchaseDataRepository;
import me.zhengjie.modules.system.service.dto.PurchaseDataDto;
import me.zhengjie.modules.system.service.dto.PurchaseDataQueryCriteria;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.system.repository.GodownEntryDetailRepository;
import me.zhengjie.modules.system.service.GodownEntryDetailService;
import me.zhengjie.modules.system.service.dto.GodownEntryDetailDto;
import me.zhengjie.modules.system.service.dto.GodownEntryDetailQueryCriteria;
import me.zhengjie.modules.system.service.mapstruct.GodownEntryDetailMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.stream.Collectors;

import me.zhengjie.utils.PageResult;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author 李忠臻
* @date 2024-02-24
**/
@Service
@RequiredArgsConstructor
public class GodownEntryDetailServiceImpl implements GodownEntryDetailService {

    private final PurchaseDataRepository purchaseDataRepository;
    private final GodownEntryRepository godownEntryRepository;
    private final GodownEntryDetailRepository godownEntryDetailRepository;
    private final GodownEntryDetailMapper godownEntryDetailMapper;

    @Override
    public PageResult<GodownEntryDetailDto> queryAll(GodownEntryDetailQueryCriteria criteria, Pageable pageable){
        Page<GodownEntryDetail> page = godownEntryDetailRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(godownEntryDetailMapper::toDto));
    }

    @Override
    public List<GodownEntryDetailDto> queryAll(GodownEntryDetailQueryCriteria criteria){
        return godownEntryDetailMapper.toDto(godownEntryDetailRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public GodownEntryDetailDto findById(Long id) {
        GodownEntryDetail godownEntryDetail = godownEntryDetailRepository.findById(id).orElseGet(GodownEntryDetail::new);
        ValidationUtil.isNull(godownEntryDetail.getId(),"GodownEntryDetail","id",id);
        return godownEntryDetailMapper.toDto(godownEntryDetail);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(GodownEntryDetail resources) {
        godownEntryDetailRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(GodownEntryDetail resources) {
        GodownEntryDetail godownEntryDetail = godownEntryDetailRepository.findById(resources.getId()).orElseGet(GodownEntryDetail::new);
        ValidationUtil.isNull( godownEntryDetail.getId(),"GodownEntryDetail","id",resources.getId());
        godownEntryDetail.copy(resources);
        godownEntryDetailRepository.save(godownEntryDetail);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            godownEntryDetailRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<GodownEntryDetailDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();

        for (int i = 0; i < all.size(); i++) {
            GodownEntryDetailDto godownEntryDetail = all.get(i);
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("序号", i + 1);
//            map.put("出货单号", godownEntryDetail.getGodownEntryNo());
//            map.put("项次", godownEntryDetail.getIndex());
//            map.put("入库日", godownEntryDetail.getCreateTime());
            map.put("开单日期", godownEntryDetail.getGodownEntryDate());
            map.put("入库日期", godownEntryDetail.getCreateTime());
//            map.put("产品编号", godownEntryDetail.getModel());
//            map.put("出货量", godownEntryDetail.getQuantity());
//            map.put("未税金额", godownEntryDetail.getUntaxAmount());

//            map.put("品名规格", godownEntryDetail.getProductName());
//            map.put("单位", godownEntryDetail.getUnit());
//            map.put("币别", godownEntryDetail.getCurrency());
//            map.put("单价", godownEntryDetail.getUnitPrice());
//            map.put("账款客户", godownEntryDetail.getCustomer());
//            map.put("客户简称", godownEntryDetail.getShortCustomerName());
//            map.put("订单项次", godownEntryDetail.getOrderIndex());
            map.put("B2B号", godownEntryDetail.getCustomerOrderNo());
            map.put("型号", godownEntryDetail.getModel());
            map.put("入库数", godownEntryDetail.getQuantity());
            map.put("含税金额", godownEntryDetail.getTaxAmount());
//            map.put("备注", godownEntryDetail.getRemark());
//            map.put("入库单明细ID", godownEntryDetail.getPurchaseRequestDetailId());
//            map.put("创建者", godownEntryDetail.getCreateBy());
//            map.put("更新者", godownEntryDetail.getUpdateBy());
//            map.put("创建日期", godownEntryDetail.getCreateTime());
//            map.put("更新时间", godownEntryDetail.getUpdateTime());

            if (godownEntryDetail.getPurchaseDataId() != null) {
                PurchaseData purchaseData = purchaseDataRepository.getById(godownEntryDetail.getPurchaseDataId());
                map.put("客户", purchaseData.getCustomer());
            }
            map.put("请购人", godownEntryDetail.getInitBy());
            map.put("备注", godownEntryDetail.getRemark());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public List<GodownEntryDetailDto> queryByGodownEntryId(Long godownEntryId) {
        List<GodownEntryDetail> godownEntryDetailList = godownEntryDetailRepository.findByGodownEntryId(godownEntryId);
        //更新客户名称
        for (GodownEntryDetail godownEntryDetail : godownEntryDetailList) {
            if (godownEntryDetail.getPurchaseDataId() != null) {
                PurchaseData purchaseData = purchaseDataRepository.getById(godownEntryDetail.getPurchaseDataId());
                godownEntryDetail.setCustomer(purchaseData.getCustomer());
            }
        }
        return godownEntryDetailMapper.toDto(godownEntryDetailList);
    }

    @Override
    public List<GodownEntryDetailDto> getSupplierSettlmentData(GodownEntryDetailQueryCriteria criteria) {
        List<GodownEntryDetailDto> result = new ArrayList<>();

        List<GodownEntry> godownEntryList = godownEntryRepository.findByStatus(1);
        List<Long> idList = godownEntryList.stream().map(GodownEntry::getId).collect(Collectors.toList());
        criteria.setGodownEntryId(idList);
        List<GodownEntryDetailDto> godownEntryDetailDtoList = godownEntryDetailMapper.toDto(godownEntryDetailRepository.
                findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
        Map<String, BigDecimal> supplierGroupMap = godownEntryDetailDtoList.stream().filter(d -> d.getTaxAmount() != null && d.getQuantity() != null).
                collect(Collectors.groupingBy(GodownEntryDetailDto::getSupplierName,
                        Collectors.mapping(d -> new BigDecimal(d.getQuantity()).multiply(d.getUnitPrice()), Collectors.reducing(BigDecimal.ZERO, BigDecimal::add))));

        for (Map.Entry<String, BigDecimal> entry : supplierGroupMap.entrySet()) {
            GodownEntryDetailDto dto = new GodownEntryDetailDto();
            dto.setSupplierName(entry.getKey().toString());
            dto.setTaxAmount(entry.getValue());
            result.add(dto);
        }
        return result;
//        return purchaseDataRepository.getSupplierSettlmentData(criteria.getGodownEntryDate().get(0), criteria.getGodownEntryDate().get(1));
    }
}